//
//  LSChatRoomViewController.m
//  LookScore
//
//  Created by wr on 2018/3/20.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSChatRoomViewController.h"
#import "LSChatRoomCell.h"
#import "LSChatKeyboard.h"
#import <IQKeyboardManager.h>
#import "LSChatRoomModel.h"
#import "LSSocketManeger.h"
#import "LSLoginVController.h"
#import "LSNavigationViewController.h"
#import "MBProgressHUD+MJ.h"

@interface LSChatRoomViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) LSChatKeyboard * customView;
@end

@implementation LSChatRoomViewController

- (LSChatKeyboard *)customView{
    if (!_customView) {
        _customView = [[LSChatKeyboard alloc]init];
        _customView.type = 1;
        _customView.frame = CGRectMake(0, LSScreenHeight-100-LSScareValue(185, LSScreenWidth), LSScreenWidth, 273);
        //传入当前控制器 ，方便打开相册（如放到控制器 ， 后期的逻辑过多，控制器会更加臃肿）
       
        if ([LSAccountArchive isLogin] == NO) {
            _customView.msgTextView.placeholder = @"登录后才可以发言...";
        }
        KWeakSelf(self);
        KWeakSelf(_customView);
        _customView.block = ^{
            LSLoginVController * loginVC = [[LSLoginVController alloc]init];
            loginVC.presentVCName = @"chatRoom";
            [weakself.navigationController presentRootViewController:loginVC animated:YES completion:nil];
            loginVC.loginSuccessBlock = ^{
                weak_customView.msgTextView.placeholder = @"";
                [weakself hideKeyboard];
            };
        };
        [_customView textCallback:^(NSString *text) {
            
            [weakself sendTextMessage:text];
        } target:self];
        
        [_customView keyboardChangeBack:^(CGFloat H) {
            
            [UIView animateWithDuration:0.25 animations:^{
               weakself.tableView.frame = CGRectMake(0, -H, LSScreenWidth, LSScreenHeight - LSLiveBaseViewH - 45 - 40);
                
            }];
        } target:self];
        
    }
    
    return _customView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, self.view.frame.size.height-50) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.allowsSelection = NO;
        _tableView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
        [_tableView addGestureRecognizer:tap];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)setMsgArray:(NSMutableArray *)msgArray{
    
    _msgArray = msgArray;
    [self.tableView reloadData];
    if (msgArray.count!=0) {
        [self scrollToBottom];
    }
   
    
}

- (void)zj_viewWillAppearForIndex:(NSInteger)index{
//    MyLog(@"%ld",index);
//    if (self.block) {
//        self.block(index);
//    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //系统键盘弹起通知
    [notifiCenter addObserver:self.customView selector:@selector(systemKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [notifiCenter addObserver:self.customView selector:@selector(keyboardResignFirstResponder:) name:UIKeyboardWillHideNotification object:nil];
    [self hideKeyboard];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self hideKeyboard];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LSBackGroundColor;
    [self.view addSubview:self.tableView];
    //初始化键盘
    [self.view addSubview:self.customView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.msgArray.count;
//    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LSChatRoomCell * cell = [LSChatRoomCell chatRoomTableViewCellBytableView:tableView];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    cell.model = self.msgArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    id model = self.msgArray[indexPath.row];
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LSChatRoomCell class] contentViewWidth:[tableView cellContentViewWith]];
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

#pragma mark - 滚动,点击等相关处理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self hideKeyboard];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    [self hideKeyboard];
    [notifiCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [notifiCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self hideKeyboard];
    
}

- (void)hideKeyboard{
    
     [notifiCenter postNotificationName:UIKeyboardWillHideNotification object:@(1)];
    
}

- (void)sendTextMessage:(NSString *)text{
    if ([text isEqualToString:@""] || text == nil) {
        [MBProgressHUD showError:@"输出的内容不能为空" toView:self.navigationController.view];
        
        return;
    }
    NSDictionary * dict = @{@"Msg":text,@"Cid":[LSAccountArchive account].Cid,@"CreateTime":[CommonClass getCurrentTimes]};
    NSString * jsonStr = [self convertToJsonData:dict];
    NSDictionary * dict1 = @{@"Category":@(2),@"MsgJson":jsonStr};
    MyLog(@"%@",[self convertToJsonData:dict1]);
    [self.manager ls_send:[self convertToJsonData:dict1]];
    
    [self hideKeyboard];
//    [self scrollToBottom];
}

- (void)scrollToBottom{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.msgArray.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    
}
// 字典转json字符串方法

-(NSString *)convertToJsonData:(NSDictionary *)dict{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        MyLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
//    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
//    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
//
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (void)dealloc{
    
    [notifiCenter removeObserver:self];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
